<template>
  <el-dialog title="上级类型" :visible.sync="dialogVisible" :before-close="handleClose" name="dialog">
    <!-- Tree 树形控件 -->
    <el-input v-model="searchValue" placeholder="请搜索..." suffix-icon="el-icon-search" style="margin-bottom: 15px; display: inline-block"></el-input>
    <el-tree
      node-key="dictId"
      :props="defaultProps"
      @check-change="handleCheckChange"
      ref="orgTree"
      :load="treeLoadNode"
      :check-strictly="true"
      :check-on-click-node="true"
      v-show="!searchResultData"
      lazy
      show-checkbox
    ></el-tree>
    <el-tree
      node-key="dictId"
      :props="defaultProps1"
      :data="searchResultData"
      @check-change="handleCheckChange"
      ref="orgTreeSearch"
      v-show="searchResultData"
      :check-strictly="true"
      :check-on-click-node="true"
      show-checkbox
      default-expand-all
    ></el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleCheck(true)">
        确定
        <i class="el-icon-document-checked el-icon--right"></i>
      </el-button>
      <el-button @click="handleCheck(false)">
        取消
        <i class="el-icon-refresh-left"></i>
      </el-button>
    </span>
  </el-dialog>
</template>
<script>
import { Tree, Dialog, MessageBox } from 'element-ui'
import {dictSearch, allRootDict, children} from '@/api/system/wordbook/wordbook.js'
export default {
  props: ['dialogVisible'],
  data () {
    return {
      // dialogVisible: false, // 弹框是否显示
      defaultProps: {
        label: 'dictName',
        isLeaf: 'leaf'
      },
      searchResultData: null, // 搜索后的tree数据
      dictId: '',
      nowCheckObj: [], // 当前选中的项
      searchValue: '', // 搜索框定义的默认属性
      defaultProps1: {
        label: 'name',
        isLeaf: 'leaf'
      }
    }
  },
  methods: {
    deepChild (val) {
      let $this = this
      if (val && Array.isArray(val) && val.length) {
        val.forEach(item => {
          if (typeof item === 'object') {
            item.dictId = item.id
            item.dictName = item.name
            $this.deepChild(item.children)
          }
        })
      }
    },
    // 编辑弹框关闭提示框
    handleClose () {
      // MessageBox.confirm('确认要关闭弹框吗？')
      //   .then(() => {
          this.$refs.orgTree.setCheckedKeys([]) // 点击取消按钮时取消tree1选中的数据
          this.searchValue = '' // 点击取消按钮时 清空搜索框还原到tree1显示
          this.$emit('dialogHide', false)
        // })
        // .catch(() => {})
    },
    // 编辑弹框点击按钮
    handleCheck (result) {
      if (!result) {
        return this.handleClose()
      }
      this.$refs.orgTree.setCheckedKeys([]) // 点击确定按钮时把选中数据传到父页面再取消tree1选中的数据
      this.searchValue = '' // 点击确定按钮时把选中数据传到父页面再清空搜索框还原到tree1显示
      this.$emit('dialogHide', this.nowCheckObj)
    },
    treeLoadNode (node, resolve) {
      // console.log(node.data)
      if (node.level === 0) {
        allRootDict().then(res => {
          let parentData = []
          res.data.data.forEach(e => {
            e.leaf = e.isLeaf === null || false
            parentData.push(e)
          })
          parentData.forEach(item => {
            this.defaultArrId = [ parentData[0].dictTypeId ]
            // console.log(item.dictTypeId)
          })
          // console.log(parentData)
          resolve(parentData)
        }).catch(res => {
          resolve([])
        })
      } else {
        // console.log(' 当前节点id值为：' + node.data.dictId)
        let id = node.data.dictId
        children(id).then(res => {
          let childrenList = []
          res.data.data.forEach(e => {
            e.leaf = e.isLeaf === null || false
            childrenList.push(e)
          })
          resolve(childrenList)
        }).catch(res => {
          resolve([])
        })
      }
    },
    // 选中节点变化事件
    handleCheckChange (data, checked, indeterminate) {
      // console.log(data, checked)
      // 如果是取消选中
      if (!checked) {
        // 如果取消选中，就把当前记录的那个节点对象dictId清掉
        if (this.nowCheckObj && this.nowCheckObj.dictId === data.dictId) this.nowCheckObj = {}
        return
      }
      // 选中了一个，如果之前已经选中过，就把tree中节点取消勾选
      let tempNowCheckObj = null
      if (this.nowCheckObj) tempNowCheckObj = this.nowCheckObj // 先复制一份数据到tempNowCheckObj再清掉nowCheckObj
      this.nowCheckObj = data // 换成新的对象
      // 给第一次选中的节点取消
      if (tempNowCheckObj) this.$refs.orgTree.setChecked(tempNowCheckObj, false)
    },
    // 搜索的选中节点变化事件
    // handleCheckChangeSearch (data, checked, indeterminate) {
      // this.searchValue = ''
      // this.searchResultData = null
      // this.$nextTick(() => this.$refs.orgTree.setChecked(data.dictId, checked))
    // },
    // 搜索框改变事件
    // searchFilterNode () {
    //   // this.searchValue = ''
    //   if (!this.searchValue.trim()) {
    //     this.searchResultData = null
    //     return false
    //   }
    //   this.axios.post('/eosDict/dictSearch', {dictName: this.searchValue}).then(res => {
    //     // console.log(JSON.stringify(res))
    //     // this.$refs.orgTree.filter(res.dictName)
    //     // 拿到正常tree里面,所有被选中着的对象的keys数组
    //     let checkedKeysArr = this.$refs.orgTree.getCheckedKeys()
    //     this.searchResultData = res.data.data
    //     console.log(this.searchResultData)
    //     this.$nextTick(() => {
    //       let orgTreeSearchTree = this.$refs.orgTreeSearch
    //       checkedKeysArr.forEach(v => {
    //         orgTreeSearchTree.setChecked(v, true)
    //       })
    //     })
    //   })
    // }
    // // 树菜单检索方法
    // filterNode (value, data, node) {
    //   console.log(value, data)
    //   if (!value) return true
    //   return data.dictName.indexOf(value) !== -1
    // }
  },
  watch: {
    searchValue (val) {
      if (val) {
        dictSearch({ dictName: this.searchValue })
        .then(res => {
          let eosDictDatas = res.data.data
          this.deepChild(eosDictDatas)
          this.searchResultData = eosDictDatas
          // this.formObj = JSON.parse(JSON.stringify(eosDictDatas[0]));
        })
      } else {
        this.searchResultData = null
      }
    }
  },
  components: {
    'el-tree': Tree, // 树形菜单
    'el-dialog': Dialog // 对话框
  }
}
</script>
